package com.LeeCode;

import java.util.ArrayList;
import java.util.List;

/**
 * 字典序排数
 */

public class Code386 {
    public static void main(String[] args) {
        System.out.println(new Code386().lexicalOrder(13));
    }

    public List<Integer> lexicalOrder(int n) {
        List<Integer> ans = new ArrayList<>();
        for (int i = 1; i <= 9; i++) {
            dfs(i, n, ans);
        }
        return ans;
    }

    private void dfs(int num, int n, List<Integer> ans) {
        if (num > n) return;
        ans.add(num);
        for (int i = 0; i <= 9; i++) {
            if (num * 10L + i > n) break; // 防止溢出
            dfs(num * 10 + i, n, ans);
        }
    }
}
